# -*- coding: UTF-8 -*-

import requests
import json
import re
from datetime import datetime


def run_catching(args):
    try:
        response = requests.get(args[0])
        lines = response.text.splitlines()
        index = 0
        tv_map = {}
        pattern = re.compile(r'"([^"]+)"')

        while index < len(lines) - 1:
            line = lines[index]

            if line.startswith("#EXTINF"):
                json_obj = {}

                for it in line.split(" "):
                    if "=" in it:
                        list_item = it.split("=")
                        matcher = pattern.search(list_item[1])
                        if matcher:
                            json_obj[list_item[0]] = matcher.group(1)

                url = lines[index + 1]
                group_title = json_obj.get("group-title")
                if group_title not in tv_map:
                    tv_map[group_title] = []
                tv_map[group_title].append({
                    "name": json_obj.get("tvg-name"),
                    "logo": json_obj.get("tvg-logo"),
                    "url": url
                })
            index += 1

        if tv_map:
            # with open("/mnt/sda0/Public/Download/tv.json", "w", encoding='utf-8') as file:
            with open("./tv.json", "w", encoding='utf-8') as file:
                json.dump(tv_map, file, ensure_ascii=False)
            print(f"获取成功 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        else:
            print(f"获取失败 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

    except Exception as e:
        print(f"获取失败 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} {str(e)}")
        print(e)


if __name__ == '__main__':
    run_catching(["https://raw.githubusercontent.com/vbskycn/iptv/master/tv/iptv4.m3u"])
